package com.doform.android.xianggucheng.activity.login;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;

import com.alibaba.fastjson.JSON;
import com.doform.android.xianggucheng.IApplication;
import com.doform.android.xianggucheng.R;
import com.doform.android.xianggucheng.activity.BaseActivity;
import com.doform.android.xianggucheng.activity.MainActivity;
import com.doform.android.xianggucheng.bean.LoginBean;
import com.doform.android.xianggucheng.bean.URLBean;
import com.doform.android.xianggucheng.bean.request_bean.ReqLoginBean;
import com.doform.android.xianggucheng.help.AppHelp;
import com.doform.android.xianggucheng.retrofit.ApiSpecTransformer.DialogTransformer;
import com.doform.android.xianggucheng.retrofit.HttpManager;
import com.doform.android.xianggucheng.retrofit.subscriber.ErrorHandleSubscriber;
import com.doform.android.xianggucheng.service.PushService;
import com.doform.android.xianggucheng.utils.Constans;
import com.doform.android.xianggucheng.utils.KeyBoardUtils;
import com.doform.android.xianggucheng.utils.SP;
import com.doform.android.xianggucheng.utils.TsUtils;
import com.doform.android.xianggucheng.utils.http.HttpUtils;
import com.doform.android.xianggucheng.view.impl.ILoginView;
import com.igexin.sdk.PushManager;
import com.zhy.http.okhttp.callback.StringCallback;

import butterknife.BindView;
import butterknife.OnClick;
import cn.f_ms.runtimepermission.simple.PermissionRefuseResultHelper;
import cn.f_ms.runtimepermission.simple.ShowRequestPermissionRationaleListener;
import cn.f_ms.runtimepermission.simple.SimpleRuntimePermission;
import io.reactivex.annotations.NonNull;
import okhttp3.Call;

public class MaLoginActivity extends BaseActivity implements ILoginView {

    @BindView(R.id.et_phone)
    EditText mPhone;

    @BindView(R.id.et_password)
    EditText mPassword;

    @BindView(R.id.progressBar)
    ProgressBar mProgressBar;

    @OnClick(R.id.ll)
    void ll() {
        KeyBoardUtils.closeKeybord(mPassword, this);
    }

    @Override
    protected int layoutResId() {
        return R.layout.activity_manlogin;
    }

    @Override
    protected void init() {
        if (Build.VERSION.SDK_INT >= 23) {
            requestPermission();
        }
        if (!AppHelp.getInstance().getToken().equals("")) {
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            finish();
        }
    }

    private void initURL() {
        HttpUtils.getRequest(Constans.URl, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                TsUtils.showToast("服务器开小差了...");
                showDialog();
            }

            @Override
            public void onResponse(String response, int id) {
                URLBean urlBean = JSON.parseObject(response, URLBean.class);
//                HttpManager.init(urlBean.getPro().getApiurl());
            }
        });
    }

    private void showDialog() {

        new AlertDialog.Builder(this)
                .setTitle("网络错误")
                .setMessage("服务器开小差了...")
                .setPositiveButton("点击重试",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                initURL();
                                dialog.dismiss();
                            }
                        })
                .
                        setNegativeButton("点击退出",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        SP.clear(mContext);
                                        IApplication.getInstance().destory();
                                        finish();
                                        dialog.dismiss();
                                    }
                                }
                        )
                .show();
    }

    private void beforeLogin() {

        if (TextUtils.isEmpty(getPhone())) {
            TsUtils.showToast("请输入手机号");
            return;
        }
//        else if (RexUtils.isMobileNO(getPhone())) {
//            TsUtils.showToast("手机号格式不正确");
//            return;
//        }
        else if (TextUtils.isEmpty(getPassword())) {
            TsUtils.showToast("请输入密码");
            return;
        }
//        else if (RexUtils.rexCheckPassword(getPassword())) {
//            TsUtils.showToast("密码格式不正确");
//            return;
//        }
        login();
    }

    private void login() {
        HttpManager.instance()
                .login(new ReqLoginBean(getPhone(), getPassword()))
                .compose(new DialogTransformer<LoginBean>(mProgressBar))
                .subscribe(new ErrorHandleSubscriber<LoginBean>() {
                    @Override
                    public void onNext(@NonNull LoginBean dataBean) { // debug
                        AppHelp.getInstance().setUserName(getPhone());
                        AppHelp.getInstance().setPassrod(getPassword());
                        toSuccsess();
                    }
                });


    }


    @Override
    protected void showView() {
    }

    @Override
    public String getPhone() {
        return mPhone.getText().toString().trim();
    }

    @Override
    public String getPassword() {
        return mPassword.getText().toString().trim();
    }

    @Override
    public void showLoading() {
        mProgressBar.setVisibility(View.VISIBLE);
    }

    @Override
    public void hideLoading() {
        mProgressBar.setVisibility(View.GONE);
    }

    @Override
    public void toSuccsess() {
        startActivity(new Intent(this, MainActivity.class));
        finish();
    }


    private void requestPermission() {
        SimpleRuntimePermission simplePermission = new SimpleRuntimePermission(this);

        simplePermission.request(
                new SimpleRuntimePermission.PermissionListener() {
                    @Override
                    public void onAllPermissionGranted() {
                        initPush();
                    }

                    @Override
                    public void onPermissionRefuse(PermissionRefuseResultHelper resultHelper) {
                        TsUtils.showToast("没有获取到权限，有订单时将无法提醒");
                    }
                }
                , new ShowRequestPermissionRationaleListener() {
                    @Override
                    public void onShowRequestPermissionRationale(final ShowRequestPermissionRationaleControler controler, String[] permissions) {
                        new AlertDialog.Builder(MaLoginActivity.this)
                                .setTitle("请求权限")
                                .setMessage("获取权限，当有新订单时做提醒")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        controler.doContinue();
                                    }
                                })
                                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        controler.doCancel();
                                    }
                                })
                                .create()
                                .show();
                    }

                    @Override
                    public void onRequestPermissionRationaleRefuse(String[] permissions) {
                        TsUtils.showToast("用户请求权限失败");
                    }
                }
                , android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_PHONE_STATE
        );
    }

    private void initPush() {
        PushManager.getInstance().initialize(this.getApplicationContext(), PushService.class);
    }

    @OnClick({R.id.btn_login, R.id.btn_register, R.id.btn_Retrieve})
    public void onclick(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
                beforeLogin();
                break;
            case R.id.btn_register:
                startActivity(new Intent(this, RegisterActivity.class));
                break;
            case R.id.btn_Retrieve:
                startActivityForResult(new Intent(this, RetrievePassWordActivity.class)
                        .putExtra(Constans.EXTRA_RETRIEVE, getPhone()), Constans.REQUEST_RETRIEVE);
                break;
            default:
                break;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null) {
            switch (requestCode) {
                case Constans.REQUEST_RETRIEVE:
                    String phone = data.getStringExtra(Constans.EXTRA_LOGIN);
                    mPhone.setText(phone);
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
